<script lang="ts" setup>
import * as CheckoutConfigApi from '@/api/client-mall/product/sku/checkout-config'
import DynamicConfigForm from './components/dynamic-config-form.vue'
import FixedConfigForm from './components/fixed-config-form.vue'
import * as DivisionApi from '@/api/client-mall/product/sku/division'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('套餐分润配置') // 弹窗的标题
// 分帐配置
const fixedBonus = ref()
const defaultFormData: CheckoutConfigApi.CheckoutConfigVO = {
  id: '',
  skuId: '',
  agentBonus: '{}',
  inviteBonus: '{}',
  saleBonus: '{}',
  fixedBonus: '[]'
}

const skuIdSave = ref()
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref<CheckoutConfigApi.CheckoutConfigVO>({ ...defaultFormData })
const formRef = ref() // 表单 Ref
const formType = ref('') // 表单的类型：create - 新增；update - 修改

/** 打开弹窗 */
const open = async (skuId: string) => {
  dialogVisible.value = true
  skuIdSave.value = skuId
  resetForm()
  // 修改时，设置数据
  formLoading.value = true
  try {
    // 获取详情
    const res = await CheckoutConfigApi.get(skuId)
    console.log('fixedBonus.value11111', fixedBonus.value)
    fixedBonus.value = []
    // 获取分帐规则
    const data = await DivisionApi.getBySkuId(skuId)
    const newDivision = data.map((item) => {
      return {
        mode: item.divisionModel === 1 ? 'amount' : 'percent',
        value: item.divisionProfit ? item.divisionProfit : item.divisionAmount,
        account: item.receiverAlias,
        delay: 0,
        type: 0
      }
    })

    if (res && data) {
      formType.value = 'update'
      formData.value = res
      fixedBonus.value = newDivision
    } else {
      formType.value = 'create'
      formData.value = { ...defaultFormData, skuId }
    }
  } finally {
    formLoading.value = false
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

// 创建分润规则
const createReceiver = () => {
  const data = fixedBonus.value.map((item) => {
    const obj = {
      skuId: skuIdSave.value,
      mchDivisionReceiverId: item.account, //分账账号id
      divisionModel: item.mode === 'amount' ? 1 : 2, //分账模型，1：金额，2：百分比
      divisionProfit: item.value, //分账比例 最高0.3
      divisionAmount: item.value
    }
    // 判断分帐模型
    item.mode === 'amount' ? delete obj['divisionProfit'] : delete obj['divisionAmount']
    return obj
  })
  console.log(data)
  DivisionApi.createReceiver(data).then((res) => {
    console.log(res)
  })
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  // if (!formRef) return
  // const valid = await formRef.value.validate()
  // if (!valid) return
  // 提交请求
  formLoading.value = true
  console.log(fixedBonus)
  try {
    const data = formData.value as unknown as CheckoutConfigApi.CheckoutConfigVO

    console.log('data', data)
    createReceiver()
    if (formType.value === 'create') {
      // 新增
      await CheckoutConfigApi.create(data)
      message.success(t('common.createSuccess'))
    } else {
      // 修改
      await CheckoutConfigApi.update(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = { ...defaultFormData }
  formRef.value?.resetFields()
}
</script>

<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <!-- 动态分润 -->
    <h1 class="text-lg mb-1">动态返佣</h1>
    <el-tabs type="border-card">
      <!-- 签单 -->
      <el-tab-pane label="推广奖励">
        <dynamic-config-form v-model="formData.saleBonus" />
      </el-tab-pane>

      <!-- 邀请人 -->
      <el-tab-pane label="邀请奖励">
        <dynamic-config-form v-model="formData.inviteBonus" />
      </el-tab-pane>
    </el-tabs>

    <!-- 固定分润 -->
    <fixed-config-form v-model="fixedBonus" />

    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
